package com.czxy.changgou3.com.czxy.changgou3.controller;

import com.czxy.changgou3.com.czxy.changgou3.service.UserService;
import com.czxy.changgou3.pojo.User;
import com.czxy.vo.BaseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author zhangmengxiang1@itcast.cn
 * @version 1.0
 * @date 2020/4/21
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 根据用户名查询用户
     * @param user
     * @return
     */
    @PostMapping("/checkusername")
    public BaseResult check(@RequestBody User user){
        //查询用户
        User byUsername = userService.findByUsername(user.getUsername());
        //判断
        if (byUsername != null){
            return BaseResult.error("用户名已经存在");
        }else {
            return BaseResult.ok("用户名可用");
        }
    }

    /**
     * 根据手机号查询用户
     *  手机号检查
     * @param user
     * @return
     */
    @PostMapping("/checkmobile")
    public BaseResult checkMobile(@RequestBody User user){
        User byMobile = userService.findByMobile(user.getMobile());
        if (byMobile != null){
            return BaseResult.error("手机号已被注册");
        }
        return BaseResult.ok("手机号可用");
    }

    /**
     * 用户注册
     * @param user
     * @return
     */
    @PostMapping("/register")
    public BaseResult register(@RequestBody User user){
        //服务端校验
        //1. 校验用户名
        User byUsername = userService.findByUsername(user.getUsername());
        if (byUsername != null){
            return BaseResult.error("用户名已经存在");
        }
        //2.校验手机号
        byUsername = userService.findByMobile(user.getMobile());
        if (byUsername != null){
            return BaseResult.error("电话号码已经存在");
        }
        //验证码
        String code =redisTemplate.opsForValue().get("sms_register"+user.getMobile());
        //删除redis中的验证吗
        redisTemplate.delete("sms_register"+user.getMobile());
        if (code == null){
            return BaseResult.error("验证码失效");
        }
        if (!code.equals(user.getCode())){
            return BaseResult.error("验证码不正确");
        }
        //注册
        userService.register(user);
        return BaseResult.ok("注册成功");
    }

    /**
     * 通过用户名查询
     * @return
     */
    @PostMapping("/findByUsername")
    public User findByUsername(@RequestBody User user){
        //查询用户
        User findUser = userService.findByUsername(user.getUsername());
        return findUser;
    }
}
